import pymysql
import random
import string
from datetime import datetime, timedelta
import time

# 数据库连接配置
config = {
    'user': 'root',
    'password': '123456',
    'host': 'localhost',
    'database': 'QQmusic',
    'charset': 'utf8mb4'
}


def insert_data(stop_event):
    try:
        # 连接到数据库
        connection = pymysql.connect(**config)
        with connection.cursor() as cursor:
            # 创建表
            create_table_query = """
            CREATE TABLE IF NOT EXISTS `test` (
              `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
              `CmId` varchar(255) DEFAULT NULL COMMENT '用户id',
              `Avatar` varchar(255) DEFAULT NULL,
              `Nick` varchar(255) DEFAULT NULL,
              `Content` longtext,
              `Location` varchar(20) DEFAULT NULL,
              `PubTime` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
              `PraiseNum` int(11) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1857 DEFAULT CHARSET=utf8mb4;
            """
            cursor.execute(create_table_query)

            # 随机数据生成函数
            def random_string(length):
                return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

            def random_avatar():
                return f"https://pic{random.randint(1, 10)}.y.qq.com/qqmusic/avatar/{random_string(32)}/140"

            def random_nick():
                return ''.join(random.choices(string.ascii_letters + string.digits + '^', k=random.randint(3, 8)))

            def random_content():
                contents = [
                    "在时光长河中，每一刻的努力都是对未来的馈赠，即便道路崎岖，也不能放弃前行的信念。",
                    "生活是一场奇妙的旅程，不必总是匆匆忙忙，偶尔停下脚步，欣赏路边的风景，或许会有别样的收获。",
                    "梦想如同夜空中的繁星，看似遥远，但只要我们怀揣着勇气和坚持，就一定能够触摸到它们的光芒。",
                    "困难只是暂时的，就像乌云终究会散去，阳光总会照耀大地。相信自己，没有什么是过不去的坎。",
                    "人生没有回头路，每一次选择都像是在绘制一幅独一无二的画卷，用心去描绘，才能留下最美的痕迹。",
                    "友谊是生活中的调味剂，它能让平淡的日子变得有滋有味，珍惜身边那些真心相待的朋友。",
                    "有时候，一个微笑就能化解所有的烦恼，用乐观的心态去面对生活，你会发现世界其实很美好。",
                    "知识是无穷无尽的宝藏，不断学习，不断探索，才能让自己的人生更加丰富多彩。",
                    "每一次挫折都是成长的机会，从失败中吸取教训，我们会变得更加坚强和成熟。",
                    "爱，是世界上最强大的力量，它能温暖人心，能治愈伤痛，让我们用爱去对待身边的每一个人。"
                ]
                return random.choice(contents)

            def random_location():
                locations = [
                    "江西", "北京", "上海", "广东", "四川", "浙江", "江苏", "山东", "河南", "河北",
                    "湖南", "湖北", "福建", "安徽", "陕西", "山西", "云南", "贵州", "辽宁", "吉林",
                    "黑龙江", "海南", "甘肃", "青海", "台湾", "内蒙古", "广西", "西藏", "宁夏", "新疆"
                ]
                return random.choice(locations)

            def random_pubtime():
                start_date = datetime(2025, 1, 1)
                end_date = datetime.now()
                delta = end_date - start_date
                random_days = random.randint(0, delta.days)
                return start_date + timedelta(days=random_days)

            def random_praise_num():
                return random.randint(0, 100)

            # 插入数据
            insert_query = """
            INSERT INTO `test` (`CmId`, `Avatar`, `Nick`, `Content`, `Location`, `PubTime`, `PraiseNum`)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            """

            while not stop_event.is_set():
                cm_id = f"1!{random_string(32)}"
                avatar = random_avatar()
                nick = random_nick()
                content = random_content()
                location = random_location()
                pub_time = random_pubtime()
                praise_num = random_praise_num()

                data = (cm_id, avatar, nick, content, location, pub_time, praise_num)
                cursor.execute(insert_query, data)
                connection.commit()
                time.sleep(1)  # 每秒插入一次

    except pymysql.Error as err:
        print(f"发生错误: {err}")
    finally:
        if connection:
            connection.close()
            print("数据库连接已关闭")